namespace Yaaf.WP7.NativeAccess.ComWrapper.HTC.COM_DMXML
{
    using System;
    using System.IO;
    using System.Text;
    using System.Threading;

    using Microsoft.Phone.InteropServices;

    using Yaaf.Wp7.AdvancedExplorer;
    using Yaaf.WP7.NativeAccess.Helper;

    internal class ProvisionXml
    {
        private IProvisionXML native;

        public ProvisionXml()
        {
            if (ComBridge.RegisterComDll("COM_DMXML.dll", new Guid("9B0F4E01-7172-4A75-86AC-7F27AA9DD02D")) != 0)
            {
                throw new RegisterComException("RegisterComDll Failed.");
            }
            native = (IProvisionXML)new CProvisionXML();
        }

        public void RestartDevice()
        {
            var errorCode = native.DMResetDevice();
            if (0L == errorCode)
            {
                throw new Exception("Error while restarting: " + errorCode);
            }
        }

        public void Provision(string xml)
        {
            StringBuilder strXml = new StringBuilder(xml);
            long length = xml.Length;
            var returnCode = native.DMProvisionXML(strXml, length);
            Thread.Sleep(500);
            if (returnCode != 0)
            {
                Logger.Instance.WriteLine("HTC Provisioning (ReturnCode: {0}, XMLDATA: {1})", returnCode, xml);
            }
        }
    }
}